<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SVG Test</title>
    <link rel="stylesheet" href="js/svg/svg.select.min.css">

    <script src="js/svg/svg.min.js"></script>
    <script src="js/svg/svg.draggable.min.js"></script>
    <script src="js/svg/svg.select.min.js"></script>
    <script src="js/svg/svg.resize.min.js"></script>
</head>
<body>
<div id="drawing" style="border:1px solid #c3c3c3;"></div>

<div style="margin-top: 16px;">
    <button onclick="clearSelectedRect(true)">删除选择的方块</button>
    <button onclick="printAllRects()">输出所有方块</button>
</div>

<script>
    function test() {
        if (!SVG.supported) {
            alert('SVG not supported');
            return;
        }
        initSVG(620, 444);
    }

    var draw;

    // 表示鼠标是否按下，全局
    var mouseDown;

    // 表示鼠标是否在rect中
    var mouseInRect;

    // 记录鼠标按下的起始坐标
    var startX, startY;
    // 当前正在绘制的矩形
    var rect;
    // 当前选中的方块
    var selectedRect;

    /**
     * 初始化默认方块
     */
    function initDefaultRects(width, height) {
        var defaultRect = draw.rect(100, 100).fill("#f06").opacity(0.5).move(50, 50);
        defaultRect.data('key', {data: Math.random()});
        addRectListener(defaultRect, width, height);
    }

    function initSVG(width, height) {
        var drawingDiv = document.getElementById("drawing");
        drawingDiv.style.width = width + "px";
        drawingDiv.style.height = height + "px";

        draw = SVG('drawing').size(width, height);
        draw.viewbox(0, 0, width, height);
        // 设置底图
        draw.image('test.jpg');

        draw.on("mousedown", function (e) {
            if (mouseInRect) {
                return;
            }
            console.log("down x: " + e.offsetX + ", y: " + e.offsetY);

            mouseDown = true;
            startX = e.offsetX;
            startY = e.offsetY;

            clearSelectedRect(false);

            // 创建rect，并监听事件
            rect = draw.rect().fill("#f06").opacity(0.5).move(startX, startY);
            addRectListener(rect, width, height);
        });
        draw.on("mousemove", function (e) {
            if (!mouseDown) {
                return;
            }
            console.log("move x: " + e.offsetX + ", y: " + e.offsetY);
            changeRectSize(startX, startY, e.offsetX, e.offsetY);
        });
        draw.on("mouseup", function (e) {
            if (!mouseDown) {
                return;
            }
            console.log("up x: " + e.offsetX + ", y: " + e.offsetY);

            mouseDown = false;
            changeRectSize(startX, startY, e.offsetX, e.offsetY);

            var width = rect.attr("width");
            var height = rect.attr("height");
            console.log("width: " + width + ", height: " + height);

            if (width == 0 || height == 0) {
                // 移除宽或高为0的矩形
                rect.remove();
                rect = null;
            } else {
                // 这里存储数据，点击的时候可以取出数据
                rect.data('key', {data: Math.random()});
            }
        });

        initDefaultRects(width, height);
    }

    /**
     * 给方块添加事件
     * @param rect
     */
    function addRectListener(rect, width, height) {
        rect.on("click", function (e) {
            console.log(this.data('key').data);

            if (this !== selectedRect) {
                clearSelectedRect(false);
            }

            this.draggable({
                minX: 0, minY: 0, maxX: width, maxY: height
            });
            this.selectize({rotationPoint: false}).resize();

            selectedRect = this;
        });
        rect.on("mouseover", function (e) {
            mouseInRect = true;
        });
        rect.on("mouseout", function (e) {
            mouseInRect = false;
        });
    }

    /**
     * 清除选中的方块
     * @param remove 是否删除
     */
    function clearSelectedRect(remove) {
        if (selectedRect) {
            selectedRect.draggable(false);
            selectedRect.selectize(false);
            if (remove) {
                selectedRect.remove();
            }
        }
        selectedRect = null;
    }

    /**
     * 动态调整矩形大小
     * @param startX
     * @param startY
     * @param endX
     * @param endY
     */
    function changeRectSize(startX, startY, endX, endY) {
        var width = endX - startX;
        var height = endY - startY;
        if (width < 0 && height < 0) {
            rect.move(endX, endY);
        } else if (width < 0) {
            rect.move(endX, startY);
        } else if (height < 0) {
            rect.move(startX, endY);
        }
        rect.size(Math.abs(width), Math.abs(height));
    }

    function printAllRects() {
        var children = draw.children();
        for (var i = 0; i < children.length; i++) {
            var child = children[i];
            if (child.type === 'rect') {
                console.log("width: " + child.attr('width') + ", height: " + child.attr('height') + ", data: " + child.data('key').data);
            }
        }
    }

    window.onload = test;
</script>
</body>
</html>